package com.yunxi.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * 一次性令牌过滤器工厂
 *
 * @author: lidy
 * @date: 2025-01-20 21:40
 */
@Component
public class OnceTokenGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {

            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    System.out.println("一次性令牌过滤器执行了");
                    // 给响应头添加一个一次性令牌，支撑 uuid，jwt 等
                    ServerHttpResponse response = exchange.getResponse();
                    HttpHeaders headers = response.getHeaders();

                    // 默认为配置的值
                    String value = config.getValue();
                    // 判断是否为加密方式
                    if ("uuid".equalsIgnoreCase(value)) {
                        value = UUID.randomUUID().toString();
                    }
                    if ("jwt".equalsIgnoreCase(value)) {
                        value = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIiwiaWF0IjoxNjc0NTQ0MDAwLCJleHAiOjE2NzQ1NDc2MDB9.5BkT7kH8R9K6uZ0Z6GzX9R8U0J8eX8R9K6uZ0Z6GzX9R8";
                    }

                    headers.add(config.getName(), value);
                }));
            }

        };
    }

}
